#!/usr/bin/env python
import urlparse
import urllib
import httplib
import json
import datetime

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
 
DEBUG = True


SERVER = "http://localhost" #"http://valtoapp.appspot.com" 
PORT = 8080 #80

# global utils
dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None
  
FORMS_HTML = r"""
<html>
<head><title>Valto Simluator</title></head>
 
<p><b>/events</b> 
<form name="listevents" action="/listevents" method="GET">
Facebook Token: <input type="text" name="fbaccesstoken" /><br/>
Location Long: <input type="text" name="location_lon" /><br/>
Location Lat: <input type="text" name="location_lat" /><br/>
<input type="submit" value="Submit" />
</form></p>

<p><b>/userProfile</b> 
<form name="userProfile" action="/userProfile" method="GET">
Facebook Token: <input type="text" name="fbaccesstoken" /><br/>
<input type="submit" value="Submit" />
</form></p>

<p><b>/events/new</b> 
<form name="newevent" action="/newevent" method="GET">
Facebook Token: <input type="text" name="fbaccesstoken" /><br/>
Name: <input type="text" name="eventname" /></br>
Description: <input type="text" name="eventdesc" /></br>
Location Long: <input type="text" name="location_lon" /><br/>
Location Lat: <input type="text" name="location_lat" /><br/>
Radius: <input type="text" name="radius" /><br/>
Start_date: <input type="text" name="start_date" /><br/>
End_date: <input type="text" name="end_date" /><br/>
<input type="submit" value="Submit" />
</form></p>


<p><b>/event/(event_id)/newitem</b> 
<form name="postnewitem" action="/postnewitem" method="GET">
Facebook Token: <input type="text" name="fbaccesstoken" /><br/>
Event ID: <input type="text" name="eventid" /></br>
Comment: <input type="text" name="comment" /><br/>
photo: <input type="text" name="photo" /><br/>
smallPhoto: <input type="text" name="smallPhoto" /><br/>
Thumbnail Photo: <input type="text" name="thumbnail" /><br/>
<input type="submit" value="Submit" />
</form></p>


<p><b>/event/(event_id)/feed</b> 
<form name="feed" action="/feed" method="GET">
Facebook Token: <input type="text" name="fbaccesstoken" /><br/>
Event ID: <input type="text" name="eventid" /></br>
From_date: <input type="text" name="from_date" /><br/>
lastUpdate: <input type="text" name="lastUpdate" /><br/>
Maximum_items: <input type="text" name="maximum_items" /><br/>
order: <input type="text" name="order" /><br/>
fromUser: <input type="text" name="fromUser" /><br/>
<input type="submit" value="Submit" />
</form></p>

<p><b>/event/(event_id)/update</b> 
<form name="update" action="/update" method="PUT">
Facebook Token: <input type="text" name="fbaccesstoken" /><br/>
Event ID: <input type="text" name="eventid" /></br>
Name: <input type="text" name="eventname" /></br>
Description: <input type="text" name="eventdesc" /></br>
Location Long: <input type="text" name="location_lon" /><br/>
Location Lat: <input type="text" name="location_lat" /><br/>
Radius: <input type="text" name="radius" /><br/>
Start_date: <input type="text" name="start_date" /><br/>
End_date: <input type="text" name="end_date" /><br/>
<input type="submit" value="Submit" />
</form></p>

<p><b>/event/(event_id)/delete</b> 
<form name="delete" action="/delete" method="PUT">
Facebook Token: <input type="text" name="fbaccesstoken" /><br/>
Event ID: <input type="text" name="eventid" /></br>
<input type="submit" value="Submit" />
</form></p>

<p><b>/event/(event_id)/item</b> 
<form name="deleteItem" action="/item" method="DELETE">
Facebook Token: <input type="text" name="fbaccesstoken" /><br/>
Event ID: <input type="text" name="eventid" /></br>
Item ID: <input type="text" name="itemid" /></br>
<input type="submit" value="Submit" />
</form></p>

<p><b>/event/(event_id)/share</b> 
<form name="share" action="/share" method="GET">
Facebook Token: <input type="text" name="fbaccesstoken" /><br/>
Event ID: <input type="text" name="eventid" /></br>
<input type="submit" value="Submit" />
</form></p>

<p><b>/event/(event_id)/exportPhotos</b> 
<form name="exportPhotos" action="/exportPhotos" method="GET">
Facebook Token: <input type="text" name="fbaccesstoken" /><br/>
Event ID: <input type="text" name="eventid" /></br>
<input type="submit" value="Submit" />
</form></p>

</html>
"""
 
class ValtoSimulator (BaseHTTPRequestHandler):   
    def do_GET(self):
        parsed_path = urlparse.urlparse(self.path)
        try:
            params = dict([p.split('=') for p in parsed_path[4].split('&')])
        except:
            params = {}
                            
        if self.path.find("/postnewitem") == 0:            
            # read input parameter
            fbtoken = params['fbaccesstoken']
            eventid = params['eventid']
            comment = params['comment']
            photo = urllib.unquote(params['photo'])
            smallPhoto = urllib.unquote(params['smallPhoto'])
            thumbnail = urllib.unquote(params['thumbnail'])
            
            # send a request to Valto Webapp API
            body = json.dumps({'comment': comment, 'photo': photo, 'smallPhoto':smallPhoto, 'thumbnail' : thumbnail})
            headers = {"facebook-access-token": fbtoken,"Content-type": "application/json", 'Content-Length': str(len(body))}
            conn = httplib.HTTPConnection(urlparse.urlparse(SERVER).hostname, PORT)
            conn.request("POST", "/event/" + str(eventid), body, headers)
            resp = conn.getresponse()
            respBody = resp.read()
            
            # send back the API call response
            self.send_response(resp.status)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(respBody)))
            self.end_headers()
            self.wfile.write(respBody)
            
            return
        
        elif self.path.find("/feed") == 0:
            # read input parameter
            fbtoken = params['fbaccesstoken']
            eventid = params['eventid']
            from_date = params['from_date'];
            lastUpdate = params['lastUpdate'];
            maximum_items = params['maximum_items']
            order = params['order']
            fromUser = params['fromUser']
            
            if from_date == "" or from_date == "now":
                from_date = datetime.datetime.now()
            
            if lastUpdate == "" or lastUpdate == "now":
                lastUpdate = datetime.datetime.now()
            
            # send a request to Valto Webapp API
            headers = {"facebook-access-token": fbtoken}
            conn = httplib.HTTPConnection(urlparse.urlparse(SERVER).hostname, PORT)
            conn.request("GET", "/event/" + str(eventid) + "?from_date=" + json.dumps(from_date, default=dthandler) + "&lastUpdate=" + json.dumps(lastUpdate, default=dthandler) + "&maximum_items=" + maximum_items + "&order=" + order + "&fromUser=" + fromUser , None, headers)
            resp = conn.getresponse()
            respBody = resp.read()
            
            # send back the API call response
            self.send_response(resp.status)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(respBody)))
            self.end_headers()
            self.wfile.write(respBody)
            
            return
        
        elif self.path.find("/item") == 0:
            # read input parameter
            fbtoken = params['fbaccesstoken']
            eventid = params['eventid']
            itemid = params['itemid'];
                        
            # send a request to Valto Webapp API
            headers = {"facebook-access-token": fbtoken}
            conn = httplib.HTTPConnection(urlparse.urlparse(SERVER).hostname, PORT)
            conn.request("DELETE", "/event/" + str(eventid) + "/item/" + str(itemid), None, headers)
            resp = conn.getresponse()
            respBody = resp.read()
            
            # send back the API call response
            self.send_response(resp.status)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(respBody)))
            self.end_headers()
            self.wfile.write(respBody)
            
            return
        
        elif self.path.find("/delete") == 0:
            # read input parameter
            fbtoken = params['fbaccesstoken']
            eventid = params['eventid']
                        
            # send a request to Valto Webapp API
            headers = {"facebook-access-token": fbtoken}
            conn = httplib.HTTPConnection(urlparse.urlparse(SERVER).hostname, PORT)
            conn.request("DELETE", "/event/" + str(eventid), None, headers)
            resp = conn.getresponse()
            respBody = resp.read()
            
            # send back the API call response
            self.send_response(resp.status)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(respBody)))
            self.end_headers()
            self.wfile.write(respBody)
            
            return
        
        elif self.path.find("/share") == 0:
            # read input parameter
            fbtoken = params['fbaccesstoken']
            eventid = params['eventid']
                        
            # send a request to Valto Webapp API
            headers = {"facebook-access-token": fbtoken, 'Content-Length': "0"}
            conn = httplib.HTTPConnection(urlparse.urlparse(SERVER).hostname, PORT)
            conn.request("POST", "/event/" + str(eventid) + "/share", None, headers)
            resp = conn.getresponse()
            respBody = resp.read()
            
            # send back the API call response
            self.send_response(resp.status)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(respBody)))
            self.end_headers()
            self.wfile.write(respBody)
            
            return
        
        elif self.path.find("/exportPhotos") == 0:
            # read input parameter
            fbtoken = params['fbaccesstoken']
            eventid = params['eventid']
                        
            # send a request to Valto Webapp API
            headers = {"facebook-access-token": fbtoken, 'Content-Length': "0"}
            conn = httplib.HTTPConnection(urlparse.urlparse(SERVER).hostname, PORT)
            conn.request("POST", "/event/" + str(eventid) + "/exportPhotos", None, headers)
            resp = conn.getresponse()
            respBody = resp.read()
            
            # send back the API call response
            self.send_response(resp.status)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(respBody)))
            self.end_headers()
            self.wfile.write(respBody)
            
            return
        
        elif self.path.find("/listevents") == 0:
            # read input parameter
            fbtoken = params['fbaccesstoken']
            location_lon = params['location_lon']
            location_lat = params['location_lat']
            
            # send a request to Valto Webapp API
            headers = {"facebook-access-token": fbtoken}
            conn = httplib.HTTPConnection(urlparse.urlparse(SERVER).hostname, PORT)
            conn.request("GET", "/events?location_lon=" + location_lon + "&location_lat=" + location_lat, None, headers)
            resp = conn.getresponse()
            respBody = resp.read()
            
            # send back the API call response
            self.send_response(resp.status)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(respBody)))
            self.end_headers()
            self.wfile.write(respBody)
            
            return
        
        elif self.path.find("/userProfile") == 0:
            # read input parameter
            fbtoken = params['fbaccesstoken']
            
            # send a request to Valto Webapp API
            headers = {"facebook-access-token": fbtoken}
            conn = httplib.HTTPConnection(urlparse.urlparse(SERVER).hostname, PORT)
            conn.request("GET", "/userProfile", None, headers)
            resp = conn.getresponse()
            respBody = resp.read()
            
            # send back the API call response
            self.send_response(resp.status)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(respBody)))
            self.end_headers()
            self.wfile.write(respBody)
            
            return
        
        elif self.path.find("/newevent") == 0:
            # read input parameter
            fbtoken = params['fbaccesstoken']
            eventname = params['eventname']
            eventdesc = params['eventdesc']
            location_lon = params['location_lon']
            location_lat = params['location_lat']
            radius = params['radius']
            start_date = params['start_date']
            end_date = params['end_date']
            #password = params['password']
            
            if start_date == "" or start_date == "now":
            #    start_date = datetime.datetime.now()
                start_date = datetime.datetime.utcnow()
                
            #if password == "":
             #   password = "0"
                    
            if end_date == "":
               # end_date = datetime.datetime.now() + datetime.timedelta(hours = 5)
               end_date = datetime.datetime.utcnow() + datetime.timedelta(hours = 5)
            
            # send a request to Valto Webapp API
            body = json.dumps({ 'name': eventname, 'description': eventdesc, 'location_lon': float(location_lon), 'location_lat': float(location_lat), \
                                'radius' : float(radius), 'start_date': json.dumps(start_date, default=dthandler),'password': '0', 'end_date': json.dumps(end_date, default=dthandler)})
            headers = {"facebook-access-token": fbtoken,"Content-type": "application/json", 'Content-Length': str(len(body))}
            conn = httplib.HTTPConnection(urlparse.urlparse(SERVER).hostname, PORT)
            conn.request("POST", "/events", body, headers)
            resp = conn.getresponse()
            respBody = resp.read()
            
            # send back the API call response
            self.send_response(resp.status)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(respBody)))
            self.end_headers()
            self.wfile.write(respBody)
            
            return
        
        
        elif self.path.find("/update") == 0:
            # read input parameter
            fbtoken = params['fbaccesstoken']
            eventid = params['eventid']
            eventname = params['eventname']
            eventdesc = params['eventdesc']
            location_lon = params['location_lon']
            location_lat = params['location_lat']
            radius = params['radius']
            start_date = params['start_date']
            end_date = params['end_date']
            
            if start_date == "" or start_date == "now":
                start_date = datetime.datetime.now()
                
            if end_date == "":
                end_date = datetime.datetime.now() + datetime.timedelta(hours = 5)
            
            # send a request to Valto Webapp API
            body = json.dumps({ 'name': eventname, 'description': eventdesc, 'location_lon': float(location_lon), 'location_lat': float(location_lat), \
                                'radius' : float(radius), 'start_date': json.dumps(start_date, default=dthandler), 'end_date': json.dumps(end_date, default=dthandler)})
            headers = {"facebook-access-token": fbtoken,"Content-type": "application/json", 'Content-Length': str(len(body))}
            conn = httplib.HTTPConnection(urlparse.urlparse(SERVER).hostname, PORT)
            conn.request("PUT", "/event/" + str(eventid), body, headers)
            resp = conn.getresponse()
            respBody = resp.read()
            
            # send back the API call response
            self.send_response(resp.status)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(respBody)))
            self.end_headers()
            self.wfile.write(respBody)
            
            return

        else:
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(FORMS_HTML)))
            self.end_headers()
            self.wfile.write(FORMS_HTML)
            return
 
def run(server_class=HTTPServer, handler_class=ValtoSimulator):
    server_address = ('', 7000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()
 
def main():
    run()
 
if __name__ == "__main__":
    main()
